package com.ciaojian.client.service;

import com.ciaojian.core.enums.business.CouponCodeOriginEnum;
import com.ciaojian.core.mapper.ExchangeMapper;
import com.ciaojian.core.mapper.UserMemberMapper;
import com.ciaojian.core.model.ExPlan;
import com.ciaojian.core.model.Exchange;
import com.ciaojian.core.model.User;
import com.ciaojian.core.model.UserMember;
import com.ciaojian.core.service.ExchangeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * @author oxiny
 */
@Service
public class ExchangeServiceImpl extends ExchangeService<ExchangeMapper, Exchange> {
    @Resource
    private ExPlanServiceImpl exPlanService;
    @Resource
    private MemberDetailServiceImpl memberDetailService;
    @Resource
    private UserMemberServiceImpl<UserMemberMapper, UserMember> userMemberService;

    /**
     * 权益兑换
     *
     * @param user     兑换用户
     * @param exchange 兑换码
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean exchange(User user, Exchange exchange) {
        // 兑换券码
        exchange.setStatus(1);
        exchange.setUserId(user.getId());
        exchange.updateById();

        ExPlan exPlan = exPlanService.getById(exchange.getPlanId());
        // 分发券码
        memberDetailService.distributeCode(
                user.getId(),
                Optional.ofNullable(memberDetailService.getById(exPlan.getMemberDetailId())),
                CouponCodeOriginEnum.CODE_EXCHANGE
        );

        // 叠加会员权益
        return userMemberService.openVip(user, 1, 365);
    }
}
